package model

import (
	"math/rand"
	"time"
	"web_server/utils"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var ran *rand.Rand = rand.New(rand.NewSource(time.Now().Unix()))
var dbm *sqlx.DB
var dbs []*sqlx.DB

func setDB(db *sqlx.DB) {
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(200)
}

func init() {
	//主
	dbmstr := utils.Config.Section("mysql_master").Key("master").String()
	thedbm, err := sqlx.Connect("mysql", dbmstr)
	if err != nil {
		panic(err)
	}
	setDB(thedbm)
	dbm = thedbm

	//从
	slaves := utils.Config.Section("mysql_slave").Keys()
	for _, dbsstr := range slaves {
		thedbs, err := sqlx.Connect("mysql", dbsstr.String())
		if err != nil {
			panic(err)
		}
		setDB(thedbs)
		dbs = append(dbs, thedbs)
	}
}

func DBMaster() *sqlx.DB {
	return dbm
}

func DBSlaveRand() *sqlx.DB {
	return dbs[ran.Intn(len(dbs))]
}
